package com.rpc.netty.simpleNetty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class NettyServer {

  public static void main(String[] args) throws InterruptedException {

    //创建线程组，均为无限循环
    //boss只处理accept请求，将请求交给worker
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    //worker处理事件
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      //配置服务器端启动参数
      ServerBootstrap serverBootstrap = new ServerBootstrap();
      //设置两个线程组
      serverBootstrap.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)//服务器通道
          .option(ChannelOption.SO_BACKLOG, 128)//线程队列等待连接的个数
          .childOption(ChannelOption.SO_KEEPALIVE, true)//设置channel保持活动连接的状态
          .childHandler(new ChannelInitializer<SocketChannel>() {//设置处理器
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
              //给workerGroup的eventLoop对应管道设置处理器
              ch.pipeline().addLast(new NettyServerHandler());
            }
          });

      System.out.println("服务器准备好了...");
      //绑定端口，并同步，生成cf对象
      //并启动服务器
      ChannelFuture cf = serverBootstrap.bind(8888).sync();


      cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
          //操作完成
          if(future.isDone()){
            System.out.println("操作完成");
            //成功
            if (future.isSuccess()){
              System.out.println("操作成功");

              //完成之前被取消
            }else if (future.isCancelled()){
              System.out.println("操作之前被取消");
            }
          }

        }
      });



      //监听后期关闭的channel
      cf.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }

  }

}
